package com.projectzqjz.parttimework.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;

import com.projectzqjz.parttimework.App;
import com.projectzqjz.parttimework.entity.PartBaseEntity;
import com.projectzqjz.parttimework.entity.UserContactsBo;
import com.projectzqjz.parttimework.net.MyCallback;
import com.projectzqjz.parttimework.net.Task;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Response;

public class PhoneUtils {

    // 号码
    private String NUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
    // 联系人姓名
    private String NAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
    private Context context;
    //上下文对象
    //联系人提供者的uri
    private Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    public PhoneUtils(Context context) {
        this.context = context;
    }


    //获取所有联系人
    public void upLoadPhones() {
        try {
            List<UserContactsBo> phones = new ArrayList<>();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String userId = SPUtils.get(App.getContext(), "userId", "") + "";
                    ContentResolver cr = context.getContentResolver();
                    @SuppressLint("Recycle") Cursor cursor = cr.query(phoneUri, new String[]{NUM, NAME}, null, null, null);
                    assert cursor != null;
                    while (cursor.moveToNext()) {
                        UserContactsBo phoneDto = new UserContactsBo(cursor.getString(cursor.getColumnIndex(NAME)), cursor.getString(cursor.getColumnIndex(NUM)), userId);
                        Log.e("Phone", cursor.getString(cursor.getColumnIndex(NAME)));
                        phones.add(phoneDto);

                    }
                    Task.getApiService().upLoadContacts(phones).enqueue(new MyCallback<PartBaseEntity>((Activity) context) {
                        @Override
                        protected void onSuccess(Response<PartBaseEntity> response) {
//                            Log.e("uploadPhone", "上传通讯录成功！");
                        }

                        @Override
                        protected void onFailure(Throwable t) {

                        }
                    });
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}